import { useUserStore } from '@/stores/modules';
import { usePermissionsStore } from '@/stores/modules';
import NProgress from 'nprogress';
import type { Router } from 'vue-router';
import type { WhiteNameList } from './constant';

NProgress.configure({ showSpinner: false });

export const createRouterGuards = (
  router: Router,
  whiteNameList: WhiteNameList,
) => {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    if (userStore.token) {
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        if (!userStore.userId) {
          await userStore.getUserInfo();
          await usePermissionsStore().GenerateRoutes();
          const hasRoute = router.hasRoute(to.name!);
          if (!hasRoute) {
            next({ ...to, replace: true });
          } else {
            next();
          }
        } else {
          next();
        }
      }
    } else {
      if (whiteNameList.some((r) => r === to.path)) {
        next();
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath },
          replace: true,
        });
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });

  router.onError((err) => {
    console.error(err);
    console.error('路由错误');
  });
};
